<?php
require_once 'class.EDO_searcher_subquery.php';
require_once 'class.SearchCondition.php';

/**
 * @package EDO
 * @subpackage Core
 *
 */
class EDO_searcher
{
	
	public $edo_object;
	protected $subqueries;
	
	protected $sorts = array();
	protected $limit;
	
	
	/**
	 * Query object
	 *
	 * @var Query
	 */
	public $query;
	
				
	public function __construct(EDO_object_base $edo_object)
	{
		$this->edo_object = $edo_object;	
		
		LEAD::requirePackage("SQL/Query");
		$this->query = new Query($this->edo_object->ldb, false);

		$tables = $this->edo_object->getTables();
		
		foreach($tables as $tableName)
		{
			$table = $this->edo_object->ldb->getTable($tableName);
			$this->query->addJoin($table, 'INNER', "edo_objects.edoid = {$table->getName()}.edoid");
			
		}
		
		// die();
		

	}
	
	
	
	public function addSubQuery($query_type = 'and')
	{
		$counter = sizeof($this->subqueries);
		$subquery = new EDO_searcher_subquery($this, $counter, $query_type);
		$this->subqueries[$counter] = $subquery;
		return $subquery;
	}
	
	
	
	public function quickSearch($params, $operator = "=", $config = array())
	{
		if(isset($config['sort']))
		{
			foreach($config['sort'] as &$sorter)
			{
				$this->query->addOrderer($sorter);
				
				// $this->addSorter($sorter);
			}
			
		}
		
		if(isset($config['limit']))
		{
			$this->setLimit($config['limit']);
			
		}
				
		
		$subquery = $this->addSubQuery();
		
		$conds = array();
		foreach($params as $key => &$value)
		{
			$searchCond = new SearchCondition($key, $operator, $value, false);
			$subquery->addCondition($searchCond);
		}
		
		// $subquery->setConstraints($conds);
		return $this->search();
	
	}

	
	
	function search()
	{
	
	    
	    
		$this->query->addField('edo_objects.edoid', true);
		
		$whereGroup = $this->query->addWhereGroup('AND');
				
		$whereGroup->addWhereCond("edo_objects.typeid", "=", "{$this->edo_object->getTypeid()}");
			
		$subconds = array();
		$subparams = array();
		
		foreach($this->subqueries as $key => $subquery)
		{
			$subquery->process();
		}
		
		
		
		$phrase = $this->query->getSQL();	
		
		
		
		
		
		$jaari = $this->edo_object->ldb->getAll($phrase);
		$prepared = $this->edo_object->ldb->prepare($phrase);
		
		$prepared->execute();
		
		$result = $prepared->fetchAll(PDO::FETCH_COLUMN);
		
		
		return array_values($result);

		
		
		
		
		
		
		
		
		
		
		
	}
	
	
	function addSorter($sorter)
	{
		$this->sorts[] = $sorter;
	}
	
	
	function setLimit($limit)
	{
		$this->limit = $limit;
		
	}
	
	
}
